import React, { useState, useEffect } from 'react';
import * as Icon from '@ant-design/icons'
import { Menu } from 'antd';
import { Link, withRouter } from 'react-router-dom'
import menuList from "@/config/menuConfig";
import "./index.less";

// 处理 pathname
const getOpenKeys = (string, collapsed) => {
    let newStr = '',
        newArr = [],
        arr = string.split('/').map(i => '/' + i)
    for (let i = 1; i < arr.length - 1; i++) {
        newStr += arr[i]
        newArr.push(newStr)
    }
    return collapsed ? [] : newArr
}

const SideMenu = props => {
    const [state, setstate] = useState({
        openKeys: [],
        selectedKeys: []
    })

    let { openKeys, selectedKeys } = state
    let menuProps = props.collapsed ? {} : { openKeys };

    // 页面刷新的时候可以定位到 menu 显示
    useEffect(() => {
        let { pathname } = props.location
        setstate(prevState => {
            return {
                ...prevState,
                selectedKeys: [pathname],
                openKeys: getOpenKeys(pathname)
            }
        })
    }, [props]);

    // 只展开一个 SubMenu
    const onOpenChange = openKeys => {
        setstate(prevState => {
            if (openKeys.length === 0 || openKeys.length === 1) {
                return { ...prevState, openKeys }
            }
            const latestOpenKey = openKeys[openKeys.length - 1]

            // 这里与定义的路由规则有关
            if (latestOpenKey.includes(openKeys[0])) {
                return { ...prevState, openKeys }
            } else {
                return { ...prevState, openKeys: [latestOpenKey] }
            }
        })
    }

    const renderMenuItem = (item) => (
        <Menu.Item key={item.path} icon={ item.icon ? React.createElement(Icon[item.icon]) : null }>
          <Link to={item.path}>{item.title}</Link>
        </Menu.Item>
    )

    // 循环遍历数组中的子项 subs ，生成子级 menu
    const renderSubMenu = (subs) => (
      <Menu.SubMenu key={subs.path} icon={ subs.icon ? React.createElement(Icon[subs.icon]) : null } title={subs.title}>
        {subs.children && subs.children.map(item => item.children && item.children.length > 0 ? renderSubMenu(item) : renderMenuItem(item))}
      </Menu.SubMenu>
    )

    return (
        <Menu
            mode='inline'
            theme='dark'
            {...menuProps}
            selectedKeys={selectedKeys}
            onClick={({ key }) => setstate(prevState => ({ ...prevState, selectedKeys: [key] }))}
            onOpenChange={onOpenChange}>
            {menuList && menuList.map(item => {
                return item.children && item.children.length > 0 ? renderSubMenu(item) : renderMenuItem(item)
            })}
        </Menu>
    )
}

export default withRouter(SideMenu)